package interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.zffc.common.util.TraceIdUtils;

import java.util.Objects;

/**
 * @Description:
 * @Note: feign拦截器，发送feign请求时，丢失主线程请求的header信息
 * @Author: zhangfei
 **/
@Slf4j
@Component
public class FeignInterceptor  implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(Objects.nonNull(attributes)){
            String traceId = attributes.getRequest().getHeader(TraceIdUtils.TRACE_ID);
            String authorization = attributes.getRequest().getHeader("Authorization");
            if(Objects.isNull(traceId)){
                traceId = TraceIdUtils.getTraceId();
            }
            requestTemplate.header(TraceIdUtils.TRACE_ID, traceId);
        }else{
            requestTemplate.header(TraceIdUtils.TRACE_ID, TraceIdUtils.getTraceId());
        }
    }
}
